import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const router = new VueRouter({
    routes,
    mode: 'history'
})

const isLogin = Boolean(localStorage.getItem("token"));
const isUserLogin = Boolean(localStorage.getItem("user-token"))
//路由拦截（守卫）
router.beforeEach(async (to, from, next) => {
    store.commit('errors')
    NProgress.start()
    store.dispatch('systemConfig')
    if (isLogin) {
        await Promise.all([store.dispatch('admin')])
    }
    if (isUserLogin) {
        await Promise.all([store.dispatch('user')])
    }
    if (to.matched.some(route => route.meta.requiresAuth) && !isUserLogin) {
        //前台验证登录，未登录跳转到登录页面
        next('/auth/login')
    }
    if (to.matched.some(route => route.meta.auth) && !isLogin) {
        //后台需要验证但未登录
        next('/login')
    } else if (to.matched.some(route => route.meta.guest) && isLogin) {
        //该页面只能游客访问，但你已经登录了，就跳转到首页
        location.href = '/'
    } else if (to.matched.length === 0) {
        next('/error')
    }
    next()
})
router.afterEach(() => {
    NProgress.done()
})

export default router
